<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Synchronized in Java | YiChangKong For Blog</title><meta name="keywords" content="技术文档"><meta name="author" content="伊长空"><meta name="copyright" content="伊长空"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><meta name="description" content="Synchronized in JavaSynchronized In Java  Last Updated: 15-10-2019 Multi-threaded programs may often come to a situation（情况） where multiple threads try to access the same resources and finally produce">
<meta property="og:type" content="article">
<meta property="og:title" content="Synchronized in Java">
<meta property="og:url" content="https://yichangkong.gitee.io/2020/09/04/Synchronized%20in%20Java/index.html">
<meta property="og:site_name" content="YiChangKong For Blog">
<meta property="og:description" content="Synchronized in JavaSynchronized In Java  Last Updated: 15-10-2019 Multi-threaded programs may often come to a situation（情况） where multiple threads try to access the same resources and finally produce">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg">
<meta property="article:published_time" content="2020-09-04T08:34:58.000Z">
<meta property="article:modified_time" content="2022-04-28T16:24:36.693Z">
<meta property="article:author" content="伊长空">
<meta property="article:tag" content="技术文档">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://yichangkong.gitee.io/2020/09/04/Synchronized%20in%20Java/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css"><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  ClickShowText: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  justifiedGallery: {
    js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
    css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
};

var saveToLocal = {
  set: function setWithExpiry(key, value, ttl) {
    const now = new Date()
    const expiryDay = ttl * 86400000
    const item = {
      value: value,
      expiry: now.getTime() + expiryDay,
    }
    localStorage.setItem(key, JSON.stringify(item))
  },

  get: function getWithExpiry(key) {
    const itemStr = localStorage.getItem(key)

    if (!itemStr) {
      return undefined
    }
    const item = JSON.parse(itemStr)
    const now = new Date()

    if (now.getTime() > item.expiry) {
      localStorage.removeItem(key)
      return undefined
    }
    return item.value
  }
}</script><script id="config_change">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-04-29 00:24:36'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(function () {  window.activateDarkMode = function () {
    document.documentElement.setAttribute('data-theme', 'dark')
    if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
    }
  }
  window.activateLightMode = function () {
    document.documentElement.setAttribute('data-theme', 'light')
   if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
    }
  }
  const autoChangeMode = 'false'
  const t = saveToLocal.get('theme')
  if (autoChangeMode === '1') {
    const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
    const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
    const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
    const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified
    if (t === undefined) {
      if (isLightMode) activateLightMode()
      else if (isDarkMode) activateDarkMode()
      else if (isNotSpecified || hasNoSupport) {
        const now = new Date()
        const hour = now.getHours()
        const isNight = hour <= 6 || hour >= 18
        isNight ? activateDarkMode() : activateLightMode()
      }
      window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
        if (saveToLocal.get('theme') === undefined) {
          e.matches ? activateDarkMode() : activateLightMode()
        }
      })
    } else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else if (autoChangeMode === '2') {
    const now = new Date()
    const hour = now.getHours()
    const isNight = hour <= 6 || hour >= 18
    if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
    else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else {
    if (t === 'dark') activateDarkMode()
    else if (t === 'light') activateLightMode()
  }const asideStatus = saveToLocal.get('aside-status')
if (asideStatus !== undefined) {
   if (asideStatus === 'hide') {
     document.documentElement.classList.add('hide-aside')
   } else {
     document.documentElement.classList.remove('hide-aside')
   }
}})()</script><meta name="generator" content="Hexo 5.2.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="https://gitee.com/yichangkong/FigureBed/raw/master/img/20200417183933.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">45</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">9</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">45</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> Archives</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> Tags</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> Categories</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div></div></div></div><div id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url(https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg)"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">YiChangKong For Blog</a></span><span id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> Archives</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> Tags</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> Categories</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div></div><span class="close" id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></span></span></nav><div id="post-info"><h1 class="post-title">Synchronized in Java</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-09-04T08:34:58.000Z" title="发表于 2020-09-04 16:34:58">2020-09-04</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-04-28T16:24:36.693Z" title="更新于 2022-04-29 00:24:36">2022-04-29</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Java/">Java</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Java/Synchronized-in-Java/">Synchronized in Java</a></span></div><div class="meta-secondline"> <span class="post-meta-separator">|</span><span class="post-meta-pv-cv"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Synchronized-in-Java"><a href="#Synchronized-in-Java" class="headerlink" title="Synchronized in Java"></a>Synchronized in Java</h1><p><a target="_blank" rel="noopener external nofollow noreferrer" href="https://www.geeksforgeeks.org/synchronized-in-java/">Synchronized In Java</a></p>
<p><a target="_blank" rel="noopener external nofollow noreferrer" href="https://gitee.com/yichangkong/FigureBed/raw/master/img/lock.png"><img src="https://gitee.com/yichangkong/FigureBed/raw/master/img/lock.png" alt="Java - Intrinsic Locks and Synchronization"></a></p>
<p>Last Updated: 15-10-2019</p>
<p><a target="_blank" rel="noopener external nofollow noreferrer" href="http://quiz.geeksforgeeks.org/multithreading-in-java/">Multi-threaded </a>programs may often come to a situation（情况） where multiple threads try to access the same resources and finally produce erroneous and unforeseen results.</p>
<p>So it needs to be made sure by some synchronization method that only one thread can access the resource at a given point of time.</p>
<p><strong>在使用多线程程序时 可能经常会遇到多个线程尝试访问相同资源并最终产生错误和无法预料的结果的情况。</strong></p>
<p><strong>因此，多线程程序需要通过某种同步方法来确保在给定的时间点只有一个线程可以访问资源。</strong></p>
<p>Java provides a way of creating threads and synchronizing their task by using synchronized blocks.</p>
<p><strong>Java提供了一种使用同步块创建线程并同步其任务的方法。</strong></p>
<p>Synchronized blocks in Java are marked with the synchronized keyword. A synchronized block in Java is synchronized on some object. All synchronized blocks synchronized on the same object can only have one thread executing inside them at a time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block.</p>
<p><strong>Java中的已同步块都用sync关键字标记。 Java中的同步块在某些对象上同步。 在同一对象上同步的所有同步块一次只能在其中一个线程内执行。 尝试进入同步块的所有其他线程将被阻塞，直到同步块内的线程退出该块为止。</strong></p>
<p>Following is the general form of a synchronized block: 以下是同步块的一般形式</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Only one thread can execute at a time. </span></span><br><span class="line"><span class="comment">// sync_object is a reference to an object</span></span><br><span class="line"><span class="comment">// whose lock associates with the monitor. </span></span><br><span class="line"><span class="comment">// The code is said to be synchronized on</span></span><br><span class="line"><span class="comment">// the monitor object</span></span><br><span class="line"><span class="keyword">synchronized</span>(sync_object)</span><br><span class="line">&#123;</span><br><span class="line">   <span class="comment">// Access shared variables and other</span></span><br><span class="line">   <span class="comment">// shared resources</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>This synchronization is implemented in Java with a concept called monitors. Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor.</p>
<p><strong>此同步是在Java中通过一个称为监视器的概念实现的。 在给定的时间，只有一个线程可以拥有一个监视器。 当线程获取锁时，据说它已进入监视器。 试图进入锁定监视器的所有其他线程将被挂起，直到第一个线程退出监视器。</strong></p>
<p>Following is an example of multi threading with synchronized.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> Keyword.Synchronized;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> yichangkong</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@create</span> 2020-08-10-15:57</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="comment">// A Java program to demonstrate working of synchronized.</span></span><br><span class="line"><span class="comment">// A Class used to send a message</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Sender</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">send</span><span class="params">(String msg)</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;Sending\t&quot;</span> + msg);</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;Thread  interrupted.&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    System.out.println(<span class="string">&quot;\n&quot;</span> + msg + <span class="string">&quot;Sent&quot;</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Class for send a message using Threads</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ThreadedSend</span> <span class="keyword">extends</span> <span class="title">Thread</span> </span>&#123;</span><br><span class="line">  <span class="keyword">private</span> String msg;</span><br><span class="line">  Sender sender;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// Recieves a message object and a string</span></span><br><span class="line">  <span class="comment">// message to be sent</span></span><br><span class="line">  ThreadedSend(String m, Sender obj) &#123;</span><br><span class="line">    msg = m;</span><br><span class="line">    sender = obj;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// Only one thread can send a message</span></span><br><span class="line">    <span class="comment">// at a time.</span></span><br><span class="line">    <span class="keyword">synchronized</span> (sender) &#123;</span><br><span class="line">      <span class="comment">// synchronizing the snd object</span></span><br><span class="line">      sender.send(msg);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Driver class</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MySynchronized</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">    Sender snd = <span class="keyword">new</span> Sender();</span><br><span class="line">    ThreadedSend S1 = <span class="keyword">new</span> ThreadedSend(<span class="string">&quot; Hi &quot;</span>, snd);</span><br><span class="line">    ThreadedSend S2 = <span class="keyword">new</span> ThreadedSend(<span class="string">&quot; Bye &quot;</span>, snd);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Start two threads of ThreadedSend type</span></span><br><span class="line">    S1.start();</span><br><span class="line">    S2.start();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// wait for threads to end</span></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      S1.join();</span><br><span class="line">      S2.join();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;Interrupted&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Output:</p>
<p>Code</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Sending     Hi </span><br><span class="line"></span><br><span class="line"> Hi Sent</span><br><span class="line">Sending     Bye </span><br><span class="line"></span><br><span class="line"> Bye Sent</span><br></pre></td></tr></table></figure>

<p>The output is same every-time we run the program.<strong>每次我们运行程序时，输出都是相同的。意思就是同步代码块起到作用了</strong></p>
<p>In the above example, we chose to synchronize the Sender object inside the run() method of the ThreadedSend class. Alternately, we could define the <strong>whole send() block as synchronized</strong> and it would produce the same result.</p>
<p><strong>在上面的示例中，我们选择在ThreadedSend类的run（）方法内同步Sender对象。 或者，我们也可以将整个send（）块定义为已同步，并且将产生相同的结果。</strong></p>
<p>Then we don’t have to synchronize the Message object inside the run() method in ThreadedSend class.</p>
<p><strong>然后，我们不必在ThreadedSend类的run（）方法内同步Message对象。</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// An alternate implementation to demonstrate </span></span><br><span class="line"><span class="comment">// that we can use synchronized with method also. </span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Sender</span> </span></span><br><span class="line"><span class="class"></span>&#123; </span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">send</span><span class="params">(String msg)</span> </span></span><br><span class="line"><span class="function">	</span>&#123; </span><br><span class="line">		System.out.println(<span class="string">&quot;Sending\t&quot;</span> + msg ); </span><br><span class="line">		<span class="keyword">try</span></span><br><span class="line">		&#123; </span><br><span class="line">			Thread.sleep(<span class="number">1000</span>); <span class="comment">//以便于测试synchronized的有效性，就故意将线程sleep 让其他线程进行run</span></span><br><span class="line">		&#125; </span><br><span class="line">		<span class="keyword">catch</span> (Exception e) </span><br><span class="line">		&#123; </span><br><span class="line">			System.out.println(<span class="string">&quot;Thread interrupted.&quot;</span>); </span><br><span class="line">		&#125; </span><br><span class="line">		System.out.println(<span class="string">&quot;\n&quot;</span> + msg + <span class="string">&quot;Sent&quot;</span>); </span><br><span class="line">	&#125; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>We do not always have to synchronize a whole method. Sometimes it is preferable to <strong>synchronize only part of a method</strong>. Java synchronized blocks inside methods makes this possible.</p>
<p><strong>我们并不总是必须同步整个方法。 有时最好只同步一部分方法。 同步方法内部的一些方法块更加行之有效 。</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// One more alternate implementation to demonstrate </span></span><br><span class="line"><span class="comment">// that synchronized can be used with only a part of </span></span><br><span class="line"><span class="comment">// method </span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Sender</span> </span></span><br><span class="line"><span class="class"></span>&#123; </span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">send</span><span class="params">(String msg)</span> </span></span><br><span class="line"><span class="function">	</span>&#123; </span><br><span class="line">		<span class="keyword">synchronized</span>(<span class="keyword">this</span>) </span><br><span class="line">		&#123; </span><br><span class="line">			System.out.println(<span class="string">&quot;Sending\t&quot;</span> + msg ); </span><br><span class="line">			<span class="keyword">try</span></span><br><span class="line">			&#123; </span><br><span class="line">				Thread.sleep(<span class="number">1000</span>); </span><br><span class="line">			&#125; </span><br><span class="line">			<span class="keyword">catch</span> (Exception e) </span><br><span class="line">			&#123; </span><br><span class="line">				System.out.println(<span class="string">&quot;Thread interrupted.&quot;</span>); </span><br><span class="line">			&#125; </span><br><span class="line">			System.out.println(<span class="string">&quot;\n&quot;</span> + msg + <span class="string">&quot;Sent&quot;</span>); </span><br><span class="line">		&#125; </span><br><span class="line">	&#125; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>This article is contributed by <strong>Souradeep Barua</strong>. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above</p>
<p>Attention reader! Don’t stop learning now.</p>
<p><strong>本文由Souradeep Barua提供。 如果发现任何不正确的地方，或者想分享有关上述主题的更多信息，请发表评论。</strong></p>
<p><strong>读者注意！ 请不要停止学习</strong></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined" rel="external nofollow noreferrer">伊长空</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://yichangkong.gitee.io/2020/09/04/Synchronized%20in%20Java/">https://yichangkong.gitee.io/2020/09/04/Synchronized%20in%20Java/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow noreferrer" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://yichangkong.gitee.io" target="_blank">YiChangKong For Blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E6%8A%80%E6%9C%AF%E6%96%87%E6%A1%A3/">技术文档</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2020/09/04/Flutter%20%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA%E4%B9%8B%E8%BF%87%E4%BA%94%E5%85%B3%E6%96%A9%E5%85%AD%E5%B0%86/"><img class="prev-cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="onerror=null;src='/img/404.jpg'"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Flutter 环境搭建之过五关斩六将</div></div></a></div><div class="next-post pull-right"><a href="/2020/08/04/97%20Things%20Every%20Programmer%20Should%20Know/"><img class="next-cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="onerror=null;src='/img/404.jpg'"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">97 Things Every Programmer Should Know</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2020/07/29/Git Command Line/" title="Git Command Line"><img class="cover" src="https://gitee.com/yichangkong/FigureBed/raw/master/img/20201123192653.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-07-29</div><div class="title">Git Command Line</div></div></a></div><div><a href="/2020/01/28/H5 Overview/" title="H5 Overview"><img class="cover" src="https://gitee.com/yichangkong/FigureBed/raw/master/img/20201122213711.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-01-28</div><div class="title">H5 Overview</div></div></a></div><div><a href="/2020/07/04/HashTable/" title="HashTable"><img class="cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-07-04</div><div class="title">HashTable</div></div></a></div><div><a href="/2020/04/29/Redis命令行/" title="Redis命令行"><img class="cover" src="https://gitee.com/yichangkong/FigureBed/raw/master/img/20200429161847.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-04-29</div><div class="title">Redis命令行</div></div></a></div><div><a href="/2019/11/25/UML Overview/" title="UML Overview"><img class="cover" src="https://gitee.com/yichangkong/FigureBed/raw/master/img/20201122213024.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-11-25</div><div class="title">UML Overview</div></div></a></div><div><a href="/2020/11/25/DataTable/" title="DataTable"><img class="cover" src="https://gitee.com/yichangkong/FigureBed/raw/master/img/20201125100521.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-11-25</div><div class="title">DataTable</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside_content" id="aside_content"><div class="card-widget card-info"><div class="card-content"><div class="card-info-avatar is-center"><img class="avatar-img" src="https://gitee.com/yichangkong/FigureBed/raw/master/img/20200417183933.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">伊长空</div><div class="author-info__description">空气越稀薄 、风景越广阔</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">45</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">9</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">45</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener external nofollow noreferrer" href="https://github.com/CodeSnakes"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/yichangkong" rel="external nofollow noreferrer" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:changkongyi@gmail.com" rel="external nofollow noreferrer" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div></div><div class="card-widget card-announcement"><div class="card-content"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">繁华落尽一场空 ：风往尘香花已尽 <br> 		<div class="is-center"> 欢迎访问 <br> <a class="bookmark button--primary" id="bookmark-it" href="https://jq.qq.com/?_wv=1027&amp;k=rCby8DjL" rel="external nofollow noreferrer" title="" target="_self"><i aria-hidden="true"> </i><span>Join QQ Group 👍</span></a></div></div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="card-content"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Synchronized-in-Java"><span class="toc-number">1.</span> <span class="toc-text">Synchronized in Java</span></a></li></ol></div></div></div><div class="card-widget card-recent-post"><div class="card-content"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2022/04/28/JOIN-Clause/" title="JOIN_Clause"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JOIN_Clause"/></a><div class="content"><a class="title" href="/2022/04/28/JOIN-Clause/" title="JOIN_Clause">JOIN_Clause</a><time datetime="2022-04-28T15:42:04.000Z" title="发表于 2022-04-28 23:42:04">2022-04-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/03/24/Vim%E9%94%AE%E4%BD%8D%E5%9B%BE/" title="Vim键位图"><img src="https://gitee.com/yichangkong/FigureBed/raw/master/img/vi-vim-cheat-sheet-sch.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Vim键位图"/></a><div class="content"><a class="title" href="/2022/03/24/Vim%E9%94%AE%E4%BD%8D%E5%9B%BE/" title="Vim键位图">Vim键位图</a><time datetime="2022-03-24T03:32:15.000Z" title="发表于 2022-03-24 11:32:15">2022-03-24</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/01/12/requirejs%20Overview/" title="RequireJs Overview"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="RequireJs Overview"/></a><div class="content"><a class="title" href="/2021/01/12/requirejs%20Overview/" title="RequireJs Overview">RequireJs Overview</a><time datetime="2021-01-12T02:43:34.000Z" title="发表于 2021-01-12 10:43:34">2021-01-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2020/12/12/SSM%E6%9E%B6%E6%9E%84%E4%B8%8B%E7%9A%84Cors%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98/" title="SSM架构下的Cors跨域问题"><img src="https://gitee.com/yichangkong/FigureBed/raw/master/img/20201213132701.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="SSM架构下的Cors跨域问题"/></a><div class="content"><a class="title" href="/2020/12/12/SSM%E6%9E%B6%E6%9E%84%E4%B8%8B%E7%9A%84Cors%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98/" title="SSM架构下的Cors跨域问题">SSM架构下的Cors跨域问题</a><time datetime="2020-12-12T13:13:28.000Z" title="发表于 2020-12-12 21:13:28">2020-12-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2020/11/25/DataTable/" title="DataTable"><img src="https://gitee.com/yichangkong/FigureBed/raw/master/img/20201125100521.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="DataTable"/></a><div class="content"><a class="title" href="/2020/11/25/DataTable/" title="DataTable">DataTable</a><time datetime="2020-11-25T01:45:41.000Z" title="发表于 2020-11-25 09:45:41">2020-11-25</time></div></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By 伊长空</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener external nofollow noreferrer" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener external nofollow noreferrer" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    let initData = {
      el: '#vcomment',
      appId: 'xuXblFdHlR0fcnQsdkLwkqvG-gzGzoHsz',
      appKey: 'ac3XS1leXcL95PWUhYV6gx0E',
      placeholder: 'Please leave your footprints',
      avatar: 'retro',
      meta: 'nick,mail'.split(','),
      pageSize: '10',
      lang: 'en',
      recordIP: false,
      serverURLs: '',
      emojiCDN: 'https://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/',
      emojiMaps: {"tv_doge":"6ea59c827c414b4a2955fe79e0f6fd3dcd515e24.png","tv_亲亲":"a8111ad55953ef5e3be3327ef94eb4a39d535d06.png","tv_偷笑":"bb690d4107620f1c15cff29509db529a73aee261.png","tv_再见":"180129b8ea851044ce71caf55cc8ce44bd4a4fc8.png","tv_冷漠":"b9cbc755c2b3ee43be07ca13de84e5b699a3f101.png","tv_发怒":"34ba3cd204d5b05fec70ce08fa9fa0dd612409ff.png","tv_发财":"34db290afd2963723c6eb3c4560667db7253a21a.png","tv_可爱":"9e55fd9b500ac4b96613539f1ce2f9499e314ed9.png","tv_吐血":"09dd16a7aa59b77baa1155d47484409624470c77.png","tv_呆":"fe1179ebaa191569b0d31cecafe7a2cd1c951c9d.png","tv_呕吐":"9f996894a39e282ccf5e66856af49483f81870f3.png","tv_困":"241ee304e44c0af029adceb294399391e4737ef2.png","tv_坏笑":"1f0b87f731a671079842116e0991c91c2c88645a.png","tv_大佬":"093c1e2c490161aca397afc45573c877cdead616.png","tv_大哭":"23269aeb35f99daee28dda129676f6e9ea87934f.png","tv_委屈":"d04dba7b5465779e9755d2ab6f0a897b9b33bb77.png","tv_害羞":"a37683fb5642fa3ddfc7f4e5525fd13e42a2bdb1.png","tv_尴尬":"7cfa62dafc59798a3d3fb262d421eeeff166cfa4.png","tv_微笑":"70dc5c7b56f93eb61bddba11e28fb1d18fddcd4c.png","tv_思考":"90cf159733e558137ed20aa04d09964436f618a1.png","tv_惊吓":"0d15c7e2ee58e935adc6a7193ee042388adc22af.png"},
      enableQQ: false,
      path: window.location.pathname,
    }

    if (true) { 
      initData.requiredFields= ('nick'.split(','))
    }
    
    if (false) {
      const otherData = false
      initData = Object.assign({}, initData, otherData)
    }
    
    const valine = new Valine(initData)
  }

  if (typeof Valine === 'function') initValine() 
  else $.getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js', initValine)
}

if ('Valine' === 'Valine' || !false) {
  if (false) btf.loadComment(document.querySelector('#vcomment'),loadValine)
  else setTimeout(() => loadValine(), 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><script src="https://cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script></div></body></html>